﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Media;

namespace CuteRibs.MVVMLib
{
	public static class Helper
	{
		public static T Clamp<T>(T source, T min, T max) where T : IComparable<T>
		{
			if (min.CompareTo(max) == 1)
			{
				throw new ArgumentException("'max' less than 'min'");
			}

			if (source.CompareTo(min) == -1)
			{
				return min;
			}
			else if (source.CompareTo(max) == 1)
			{
				return max;
			}

			return source;
		}

		public static Color ParseColor(uint value)
		{
			byte a = 0xff;

			if (value > 0xffffff)
			{
				a = (byte)(value >> 24);
			}

			byte r = (byte)(value >> 16);
			byte g = (byte)(value >> 8);
			byte b = (byte)(value >> 0);
			return Color.FromArgb(a, r, g, b);
		}
		
		public static string EncodeHtmlString(string html)
		{
			StringBuilder sb = new StringBuilder();
			uint code;

			foreach (char c in html)
			{
				code = (uint)c;

				if (code > 127)
				{
					sb.AppendFormat("&#{0};", code);
				}
				else
				{
					sb.Append(c);
				}
			}

			return sb.ToString();
		}

		public static string GetSHA1(string source)
		{
			var sha1 = new SHA1Managed();
			var bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(source));
			var result = BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();
			sha1.Clear();
			return result;
		}
	}
}
